package com.stedu.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.stedu.bean.RespBean;
import com.stedu.bean.Student;
import com.stedu.exception.SteduException;
import com.stedu.service.StudentService;
import com.sun.deploy.net.URLEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("/admin/upload")
public class UploadController {
    @Value("${stedu.picdir}")//注入路径
    private String picdir;
    @Autowired
    private StudentService studentService;

    @PostMapping()
    public RespBean upload(MultipartFile pic) throws IOException {
        //获取图片的名字
        String filename = pic.getOriginalFilename();
        //改名字
        filename = IdUtil.getSnowflakeNextIdStr();
        //将图片保存在服务器
        pic.transferTo(new File(picdir + filename));
        return RespBean.ok("上传成功", filename);
    }

    //导出
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("全体学生注册信息", "UTF-8").replaceAll("\\+", "%50");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Student.class).sheet("模板").doWrite(studentService.selectBySname(null, null));
    }

    //导入
    @PostMapping("/upload1")
    public RespBean upload1(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Student.class, new PageReadListener<Student>(dataList -> {
            for (Student student : dataList) {
                student.setSpassword("14e1b600b1fd579f47433b88e8d85291");
                try {
                    studentService.insert(student);
                } catch (SteduException e) {
                    // 处理异常
                    throw new RuntimeException(e.getMessage()); // 可以选择抛出 RuntimeException 或者记录错误
                }
            }
        })).sheet().doRead();
        return RespBean.ok("上传成功");
    }

}
